package com.li.online.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.li.online.service.base.exceptionhandler.GuliException;
import com.li.online.service.base.result.R;
import com.li.online.service.base.result.ResultCodeEnum;
import com.li.online.service.oss.service.FileService;
import com.li.online.service.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 11465
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    OssProperties ossProperties;

    /**
     * oss文件上传
     * @param file
     * @param module
     * @return
     */
    @Override
    public String upload(MultipartFile file,String module) {//module桶的目录名称

        try {
            OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                    ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
            InputStream inputStream = file.getInputStream();
            System.out.println("inputStream = " + inputStream);
            String string = new DateTime().toString("yy/MM/dd/");
            String fileName = module+"/"+string+ UUID.randomUUID().toString().replace("-","")
                     +file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            ossClient.putObject(ossProperties.getBucketName(), fileName, inputStream);
            ossClient.shutdown();
            //https://online12138.oss-cn-shanghai.aliyuncs.com/avatar/21/10/11/a6010743c83b4e3486f13edf5461b27d.jpg
            String imgUrl = "http://"+ossProperties.getBucketName()+".oss-cn-shanghai.aliyuncs.com/"+fileName;
            System.out.println("imgUrl = " + imgUrl);
            return imgUrl;
        } catch (Exception e) {
            //throw new RuntimeException();
            //使用自己定义的异常类
            throw  new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }

    @Override
    public void delete(String path,String module) {
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        // 删除文件或目录。如果要删除目录，目录必须为空。
        //objectName代表文件在 oss桶内的路径+文件名
        String objectName = path.substring(path.lastIndexOf(module+"/"));
        ossClient.deleteObject(ossProperties.getBucketName(), objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
    }


}
